﻿using System;
using System.Data.Entity;
using System.Linq;
using IFDB.Models.Contexts;
using IFDB.Models.Tables;
using IFDB.ViewModels.PartialViewModels;
using IFDB.ViewModels.PartialViewModels.Interfaces;

namespace IFDB.ViewModels.PageViewModels
{
    public class TeamViewModel 
    {
        public TeamViewModel()
        {
        }
        
        public TeamViewModel(Guid teamId, Guid? seasonId)
        {
            using (IFDBContext db = new IFDBContext())
            {
                Team = db.Teams.Single(t => t.TeamId == teamId);
                TeamName = db.TeamNames.Where(t => t.TeamId == teamId).OrderByDescending(t => t.StartDate).First();

                var query = from teamBadge in db.TeamBadges
                            where teamBadge.TeamId == teamId
                            orderby (teamBadge.StartDate) descending
                            select teamBadge;

                TeamBadge = query.Count() == 1 ? query.Single() : null;

                StartDate = seasonId == null
                    ? db.Seasons.Single(s => s.StartDate <= DateTime.Now && s.EndDate >= DateTime.Now).StartDate
                    : db.Seasons.Single(s => s.SeasonId == seasonId).StartDate;

                EndDate = seasonId == null
                    ? db.Seasons.Single(s => s.StartDate <= DateTime.Now && s.EndDate >= DateTime.Now).EndDate
                    : db.Seasons.Single(s => s.SeasonId == seasonId).EndDate;
            }
        }

        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }
        public Team Team { get; set; }
        public TeamName TeamName { get; set; }
        public TeamBadge TeamBadge { get; set; }

        private ITeamMatchListViewModel teamMatchListViewModel;
        public ITeamMatchListViewModel TeamMatchListViewModel
        {
            get
            {
                if (teamMatchListViewModel == null)
                    teamMatchListViewModel = new TeamMatchListViewModel(Team, StartDate, EndDate);

                return teamMatchListViewModel;
            }
        }

        private TeamPersonListViewModel teamPersonListViewModel;
        public TeamPersonListViewModel TeamPersonListViewModel
        {
            get
            {
                if (teamPersonListViewModel == null)
                    teamPersonListViewModel = new TeamPersonListViewModel(Team, StartDate, EndDate);

                return teamPersonListViewModel;
            }
        }
    }
}
